package com.gt.utils;



import com.gt.annotation.FieldCutting;

import java.lang.reflect.Field;

/**
 * 对象加工工具
 */
public class ObjectUtil {

    /**
     * 转换
     * @param obj
     * @param <T>
     * @return
     */
    public static  <T> T convert(T obj){
        // 所有字符串属性长度截取
        cuttingStrFields(obj);
        return obj;
    }

    /**
     * 所有字符串属性长度截取  @FieldCutting 截取的长度
     * @param obj 对象
     * @param <T>
     * @return
     */
    public static <T> T cuttingStrFields(T obj){
        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            FieldCutting annotation = field.getAnnotation(FieldCutting.class);
            if (annotation!=null) {
                int length = annotation.value();
                if (length >= 0 && field.getType() == String.class) {
                    try {
                        field.setAccessible(true);
                        Object fieldVal = field.get(obj);
                        if (fieldVal != null) {
                            String result = XyStringUtils.cutting((String) fieldVal, length);
                            field.set(obj, result);
                        }
                    } catch (IllegalAccessException e) {
                    }
                }
            }
        }
        return obj;
    }

}
